const { app, BrowserWindow } = require('electron');
const { join } = require('path');
const express = require('express');
const cors = require('cors');
const axios = require('axios');

// 屏蔽安全警告
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';

const queryData = async (khsh, cookie) => {
    let headers = {
        'Cookie': cookie,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
        'Accept': '*/*',
        'Host': 'crm.htjs.net',
        'Connection': 'keep-alive'
    };
    const url = `https://crm.htjs.net/server/crm/khgl/ywbldzswj/getSjkhgl_jbxx.jsp?KHSH=${khsh}&_=${Date.now()}`;
    try {
        const response = await axios.get(url, { headers });
        return response.data;
    } catch (error) {
        console.error('爬取失败:', error);
        return '';
    }
};

// 创建Express服务
const createExpressServer = () => {
    const app = express();
    const port = 5001;

    // 启用CORS
    app.use(cors({
        origin: 'http://localhost:3000',
        methods: ['GET', 'POST', 'PUT', 'DELETE'],
        allowedHeaders: ['Content-Type', 'Authorization']
    }));

    // 查询单个
    app.get('/query/:code', async (req, res) => {
        try {
            const code = req.params.code;
            const token = req.query.token;
            console.log('cookie2:', token);
            console.log('Code:', code);
            const data = await queryData(code, `JSESSIONID=${token}`);
            res.json(data);
        } catch (error) {
            res.status(400).json({ error: '无效ID' });
        }
    });

    // 错误处理
    app.use((req, res) => {
        res.status(404).json({ error: "路由不存在" });
    });

    app.use((err, req, res, next) => {
        console.error(err.stack);
        res.status(500).json({ error: '服务器内部错误' });
    });

    // 启动服务器
    app.listen(port, () => {
        console.log(`Server start http://localhost:${port}`);
    });
};

// 创建浏览器窗口
const createWindow = () => {
    const win = new BrowserWindow({
        title: 'CRM税号查询助手',
        icon: join(__dirname, '../public/favicon.ico'),
        width: 800,
        height: 520,
        resizable: true,
        show: false,
        webPreferences: {
            webSecurity: false,
            nodeIntegration: true,
            contextIsolation: false
        }
    });
    win.maximize();
    win.setMenu(null);

    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL);
        //win.webContents.openDevTools();
    } else {
        win.loadFile(join(__dirname, '../dist/index.html'));
        //win.webContents.openDevTools();
    }

    win.once('ready-to-show', () => {
        win.show();
    });
};

// Electron初始化
app.whenReady().then(() => {
    createExpressServer();
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});
